import React, { useState } from "react";
import { Popup } from "antd-mobile";
import Creator from "./Creator";
import type { CreatorProps } from "./Creator";

interface GroupChatCreatorProps extends Pick<CreatorProps, "title" | "chatroom_id" | "members" | "onOk"> {
  children: React.ReactElement;
}

function GroupChatCreator(props: GroupChatCreatorProps) {
  const { children, ...restProps } = props;
  const [visible, setVisible] = useState(false);

  let child = React.Children.only(children);

  if (child.type === React.Fragment) {
    return null;
  }

  if (React.isValidElement(child as React.ReactElement<any>)) {
    const childProps = {
      ...child.props,
      onClick: () => {
        setVisible(true);
      },
    };

    child = React.cloneElement(child, childProps);
  }

  return (
    <>
      {child}
      <Popup visible={visible} destroyOnClose>
        <Creator setVisible={setVisible} multiple={true} removeCurrent={true} {...restProps} />
      </Popup>
    </>
  );
}

export default GroupChatCreator;
